#! /bin/python
# coding: utf-8

from pyzabbix import ZabbixAPI

from common.load_cfg import load_cfg
from common.enable_debug import enable_debug


class PyZabbix:
    def __init__(self, user, pwd, url):
        self.api = ZabbixAPI(url)
        self.api.login(user, pwd)

    def get_host(self):
        hosts_info = self.api.host.get(
            output="extend",
            # output=["hostid", "host"],
            selectInterfaces=["ip", "interfaces"],
            # selectParentTemplates=["templateid", "name"],
            groupids=70
        )
        return hosts_info

    def get_hostGroup(self):
        host_group_info = self.api.hostgroup.get(
            output="extend"
        )
        return host_group_info

    def get_item_info(self, hostids):
        item_info = self.api.item.get(
            # output="extend",
            output=['itemids', 'key_'],
            hostids=hostids
        )
        return item_info

    def get_template(self):
        template_info = self.api.template.get(
            output=["templateid", "name"]
            # output="extend"
        )
        return template_info

    def get_history_trigger(self):
        his = self.api.trigger.get(
            output=["triggerid", "description", "priority"],
            filter={"value": 1},
            sortfield="priority",
            sortorder="DESC",
            min_severity=1,
            skipDependent=1,
            monitored=1,
            active=1,
            expandDescription=1,
            selectHosts=['host'],
            selectGroups=['name'],
            only_true=1
        )
        return his

    def get_actionId(self):
        actionID = self.api.action.get(
            output='actionid'
        )
        return actionID

    def get_alert(self):
        ids = []
        alert_info_list = self.get_actionId()
        for alert_info in alert_info_list:
            ids.append(alert_info['actionid'])
            # if alert_info['actionid'] is not None:
            #    ids.append(alert_info['actionid'])
        alerts = []
        for id in ids:
            try:
                alert = self.api.alert.get(
                    output="extend",
                    #from_time="",
                    actionids=id
                )
                alerts = alerts + alert
            except:
                pass
                print('error:{}'.format(id))
        return alerts

    def get_host_templates(self, hostId):
        res = self.api.host.get(output=["hostid"], selectParaentTemplates=["templateid", "name"], hostids=hostId)
        return res

    def get_host_by_ip(self, IP):
        # res = self.api.host.get(filter={"interfaces":[{"ip":IP}]})
        res = self.api.host.get(
            selectGroups="extend",
            filter={"ip": IP}
        )
        return res

    def get_host_by_host(self, host):
        res = self.api.host.get(filter={"host": [host]})
        return res

    def get_templates(self):
        res = self.api.template.get(
            output=["name", "templateid", "status"]
            # output="extend"
        )
        return res

    def get_proxy(self):
        res = self.api.proxy.get(
            # output="extend"
            output=["host", "proxyid", "status"]
        )
        return res

    def get_history(self):
        res = self.api.history.get(
            output="extend",
            history=0,
            limit=5


        )
        return res

    def get_hostInterface(self, hostId):
        res = self.api.hostinterface.get(
            ouput="extend",
            hostids=hostId
        )
        return res

    def create_hostInterface(self, hostId, IP, port, type):
        res = self.api.hostinterface.create(
            hostid=hostId,
            ip=IP,
            port=port,
            type=type,
            main=0,
            dns="",
            useip=1
        )
        return res

    def create_host(self, hostname, groupId, templateId):
        res = self.api.host.create(
            host=hostname,
            groups=[{"groupid": groupId}],
            templates=[{"templateid": templateId}],
            # interfaces=[
            #    {
            #        "type": "1",
            #        "main": "1",
            #        "useip": "1",
            #        "ip": IP,
            #        "port": "10050"
            #    }
            # ]
        )
        # res=hostids
        return res

    def create_proxy(self, hostId):
        res = self.api.proxy.create(
            host="Active proxy",
            status=5,
            hosts=[{"hostid": hostId}]
        )
        return res

    def del_host_by_id(self, hostId):
        res = self.api.host.delete(hostId)
        return res

    def host_add_template(self, hostId, templateId):
        res = self.api.template.massadd(templates=templateId, hosts={"hostid": hostId})
        return res

    def del_host_template_id(self, hostId, templateId):
        res = self.api.host.update(hostid=hostId, templates_clear={"templateid": templateId})
        return res


if __name__ == "__main__":
    config = load_cfg('zbx_info')
    if config["debug"] == True:
        enable_debug("PyZabbix")
    user = config["zbx_user"]
    pwd = config["zbx_pwd"]
    url = config["zbx_url"]
    zbx = PyZabbix(user, pwd, url)
    for i in zbx.get_host():
        print(i['host'], i['interfaces'][0]['ip'])
    # alerts=zbx.get_alert()
    # for alert in alerts:
    #    with open(r'd:\test.csv','a+') as f:
    #        f.write(str(alert)+"\n")

    # for m in info:
    #    try:
    #        h=m['message'].split("\r\n")
    #        for i in h:
    #            print('{0},{1},{2},{3},{4}'.format(i['clock'],i[0].split("：")[1],i[1].split("：")[1],i[2].split("：")[1],i[3].split("：")[1]))
    #    except:
    #        print('error:{}'.format(i))
    #        pass
    # f.write('{0},{1},{2},{3},{4}\n'.format(i['clock'],i[0].split("：")[1],i[1].split("：")[1],i[2].split("：")[1],i[3].split("：")[1]))
    # print('{},{}'.format(i['clock'],i['message']))
    # print(i)

# 1.create host
# res = zbx.create_host("ywtool","10.10.205.56",31,14539)
# print(res)
# 2.config proxy mode
# res = zbx.get_hostInterface(10685)
# print(res)
# for i in res:
#    print('{},{}'.format(i['templateid'],i['name']))

# ips=["10.10.105.108","10.10.105.110","10.10.105.121","10.10.213.209","10.10.205.33","10.10.205.30","10.10.205.54","10.10.205.57","10.10.213.209","10.10.200.158","10.10.200.78","10.10.202.150","10.10.202.151","10.10.202.152","10.10.202.111","10.10.202.112","10.10.202.200","10.10.202.143","10.10.203.22","10.10.203.19","10.10.113.137","10.10.113.175","10.10.113.176","10.10.113.177","10.10.202.194","10.10.202.195","10.10.202.196","10.10.113.148","10.10.113.149","10.10.113.150","10.10.113.21","10.10.113.22","10.10.113.23","10.13.2.89","10.13.2.90","10.13.2.91","10.10.102.87","10.10.102.88","10.10.202.57","10.10.202.58","10.10.202.11","10.10.202.12","10.10.202.13","10.10.202.84","10.10.202.85","10.10.202.86","10.10.202.87","10.10.202.88"]
# for ip in ips:
#    res = zbx.get_host_by_ip(ip)
#    if len(res) == 0:
#        print(ip)

# l=[]
# for i in res:
#    #print(i['hostid'])
#    l.append(i['hostid'])
# print(l)
# info = zbx.get_item_info(l)
# print(info)
# for i in info:
#    if i['key_'].startswith('vfs.fs.size'):
#        print(i)

# for actionID in ["2","3","4","5","6","9","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32"]:
#    test=zbx.get_alert(actionID)
#    for i in test:
#        #print('{},{}'.format(i['clock'],i['message']))
#        print(i)


# print('subject:{},message:{}'.format(i['subject'],i['message'][2]))
# if 'jvm' in i['message'].lower() and 'jvm无响应' not in i['message'].lower() and '恢复内容' not in i['message'].lower():
#    print(i['subject'].split(':')[2])
#    #print(i['message'].lower())

# hosts_info = zbx.get_host_info()
# tid = []
# for info in hosts_info:
#    if len(info["interfaces"]) > 1:
#        template_info = info["parentTemplates"]
#        for i in template_info:
#            tid.append(i["templateid"])

# if ("10250" in tid):
#    print(tid)
# print(hosts_info)
# print(zbx.get_proxy())
# print(zbx.create_proxy(10255))
# ips=["10.10.113.194","10.10.213.237","10.10.203.87","10.10.113.158","10.10.203.251","10.10.203.163","10.10.203.163","10.10.203.163","10.10.213.181","10.10.213.181","10.10.201.56","10.10.201.204","10.10.201.204","10.10.201.56","10.10.202.155","10.10.203.190","10.10.213.197","10.10.203.157","10.10.113.70","10.10.113.69","10.10.201.204","10.10.213.134","10.10.213.138","10.10.201.198","10.10.213.198"]
# for ip in ips:
#    info = zbx.get_host_by_ip(ip)
#    for i in info:
#        #print(i['host'])
#        #count=len(i['groups'])
#        print(ip,i['groups'][-1]['name'])
#        #print(ip, i)
